package com.hisan.freeride.home.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;

import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.utils.MyHandlerUtil;
import com.hisan.freeride.common.utils.utils.TokenUtils;
import com.hisan.freeride.common.view.MyLinearLayoutManager;
import com.hisan.freeride.databinding.ConnectionBinding;
import com.hisan.freeride.home.adapter.ConnectionAdapter;
import com.hisan.freeride.home.model.Connection;
import com.lzy.okgo.OkGo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 创建时间 : 2017/6/8
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：紧急联络人页面
 */
public class ConnectionActivity extends BaseActivity<ConnectionBinding> {
    private ConnectionAdapter connectionAdapter;
    //拨打电话权限返回码
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private Connection listBean;
    private int type=1;


    @Override
    protected int getLayoutId() {
        return R.layout.connection;
    }

    @Override
    protected void initView() {
        mBinding.setStateModel(mStateModel);
        connectionAdapter=new ConnectionAdapter(new ArrayList<>(0));
        mBinding.rv.setLayoutManager(new MyLinearLayoutManager(this));
        mBinding.rv.setAdapter(connectionAdapter);
        mBinding.slectName.setOnClickListener(v -> startActivityForResult(AddressListActivity.class,99,null,true));
    }

    @Override
    protected void initEvent() {
        connectionAdapter.setButtonClickListener(data -> {
            if (!CollectionUtils.isNullOrEmpty(data)){
                type=2;
                listBean = data;
                getmDialog("是否删除当前联系人?", "取消", "确定").show();
            }
        });
        connectionAdapter.setItemClickListener(data -> {
            listBean = data;
            type=1;
            getmDialog("是否打开手机拨号", "取消", "确定").show();
        });
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.<List<Connection>>get(AppConfig.Contact)
                .tag(this)
                .execute(new DialogCallback<List<Connection>>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<Connection>> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())) {
                            if (isOk(response)){
                                showData();
                                if (response.body().size() >= 5) {
                                    mBinding.slectName.setVisibility(View.GONE);
                                } else {
                                    mBinding.slectName.setVisibility(View.VISIBLE);
                                }
                                if (!CollectionUtils.isNullOrEmpty(response.body()))
                                    connectionAdapter.setNewData(response.body());
                            }else {
                                showErrorView(response.code());
                            }
                        }else {
                            noData();
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<List<Connection>> response) {
                        super.onError(response);
                        showErrorView(response.code());
                    }
                });
    }

    @Override
    public void onOk() {
        super.onOk();
        if (type==1){
            // 检查是否获得了权限（Android6.0运行时权限）
            if (ContextCompat.checkSelfPermission(ConnectionActivity.this,
                    Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
                // 没有获得授权，申请授权
                if (ActivityCompat.shouldShowRequestPermissionRationale(ConnectionActivity.this,
                        Manifest.permission.CALL_PHONE)) {
                    // 弹窗需要解释为何需要该权限，再次请求授权
                    showToast("请在应用中开启电话权限");
                    // 帮跳转到该应用的设置界面，让用户手动授权
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                }else{
                    // 不需要解释为何需要该权限，直接请求授权
                    ActivityCompat.requestPermissions(ConnectionActivity.this,
                            new String[]{Manifest.permission.CALL_PHONE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE);
                }
            }else {
                // 已经获得授权，可以打电话
                if (!CollectionUtils.isNullOrEmpty(listBean)){
                    CallPhone(listBean.getMobile());
                }
            }
        }else {
            Delete();
        }

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (!CollectionUtils.isNullOrEmpty(data)){
            if (resultCode==99){
                loadData(true);
            }
        }
    }


    //删除联系人
    private void Delete() {
        OkGo.delete(AppConfig.Delcontact)
                .tag(this)
                .params("id",listBean.getId())
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (isOk(response)){
                            showToast("删除成功");
                            MyHandlerUtil.getHandler().postDelayed(() -> {
                                loadData(true);
                            },200);
                        }else {
                            showError(response);
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });

    }
    private void CallPhone(String number) {
        if (CollectionUtils.isNullOrEmpty(number)) {
            showToast("号码不能为空！");
        } else {
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
    }

    // 处理权限申请的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    if (!CollectionUtils.isNullOrEmpty(listBean))
                        CallPhone(listBean.getMobile());
                } else {
                    showToast("电话授权失败！");
                }
                break;
            }
        }
    }
}
